package com.sanpu.kxe.business.card.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanpu.library.imagechoose.PhotoPicker;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseEditActivity;
import com.sanpu.kxe.business.card.bean.DefBankOcrOutput;
import com.sanpu.kxe.business.card.bean.DefBankOutput;
import com.sanpu.kxe.business.card.contract.UpdateDefBankContract;
import com.sanpu.kxe.business.card.presenter.UpdateDefBankPresenter;
import com.sanpu.kxe.business.card.provider.CardOpenProvider;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.common.view.CommonTitleView;
import com.sanpu.kxe.jump.eventbus.ReviewPhotoEvent;
import com.sanpu.kxe.jump.imageloader.JKImageLoader;
import com.sanpu.kxe.module.specialunit.OnClickableSpanListener;
import com.sanpu.kxe.module.specialunit.SimplifySpanBuild;
import com.sanpu.kxe.module.specialunit.unit.SpecialClickableUnit;
import com.sanpu.kxe.rxservice.RequestMap;
import com.sanpu.kxe.utils.FileUtil;
import com.sanpu.kxe.utils.SoftInputUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：修改默认结算卡
 * Created by 薛勇军 on 2018/7/17.
 */

public class UpdateDefBankActivity extends BaseEditActivity implements UpdateDefBankContract.View {

    @Bind(R.id.commonTitle)
    CommonTitleView commonTitle;

    @Bind(R.id.crdFroIv)
    ImageView crdFroIv;
    @Bind(R.id.crdFro)
    ImageView crdFro;
    @Bind(R.id.crdFroCloud)
    TextView crdFroCloud;

    @Bind(R.id.crdConIv)
    ImageView crdConIv;
    @Bind(R.id.crdCon)
    ImageView crdCon;
    @Bind(R.id.crdConCloud)
    TextView crdConCloud;

    @Bind(R.id.handIv)
    ImageView handIv;
    @Bind(R.id.hand)
    ImageView hand;
    @Bind(R.id.handCloud)
    TextView handCloud;

    @Bind(R.id.idCardClaimTv)
    TextView idCardClaimTv;

    private UpdateDefBankContract.Presenter mPresenter;

    private boolean isNeedUpload = true;

    private DefBankOcrOutput mOcrOutput;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_update_bank_def;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setTitle("修改结算卡");
        mPresenter = new UpdateDefBankPresenter(this);

        SpecialClickableUnit clickableUnit = new SpecialClickableUnit(new OnClickableSpanListener() {
            @Override
            public void onClick(TextView tv, String clickText) {
                mPresenter.openOldUpdateDefBankActivity();
            }
        });
        clickableUnit.setSpecialText("请点击使用人工审核");
        clickableUnit.setNormalTextColor(ContextCompat.getColor(getContext(), R.color.c_ff3f40));
        clickableUnit.setPressTextColor(ContextCompat.getColor(getContext(), R.color.c_ff3f40));
        clickableUnit.showUnderline();
        SimplifySpanBuild build = new SimplifySpanBuild(getContext(), idCardClaimTv, "4. 如照片一直未通过，");
        build.appendSpecialUnit(clickableUnit);
        idCardClaimTv.append(build.build());
    }

    @Override
    protected void setListener() {
        super.setListener();
        commonTitle.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @OnClick({R.id.commit, R.id.crdFro, R.id.crdCon, R.id.hand})
    public void commit(View view) {
        switch (view.getId()) {
            case R.id.commit:
                if (!isRespondEvent()) return;
                if (!isNeedUpload && mOcrOutput != null) {
                    showOcrBankViewData(mOcrOutput, isNeedUpload);
                } else {
                    mPresenter.onCommit();
                }
                break;
            case R.id.crdFro:
                if (crdFroIv.getTag() != null) {
                    mPresenter.takePhoto((String) crdFroIv.getTag(),
                            CommonConfig.REQUESTCODE_DEFBANK_VIEW_CRDFRO);
                } else {
                    mPresenter.openCertificateHelpActivity(CommonConfig.TYPE_CRDFROPIC);
                }
                break;
            case R.id.crdCon:
                if (crdConIv.getTag() != null) {
                    mPresenter.takePhoto((String) crdConIv.getTag(),
                            CommonConfig.REQUESTCODE_DEFBANK_VIEW_CRDCON);
                } else {
                    mPresenter.openCertificateHelpActivity(CommonConfig.TYPE_CRDCONPIC);
                }
                break;
            case R.id.hand:
                if (handIv.getTag() != null) {
                    mPresenter.takePhoto((String) handIv.getTag(),
                            CommonConfig.REQUESTCODE_DEFBANK_VIEW_IDHAND);
                } else {
                    mPresenter.openCertificateHelpActivity(CommonConfig.TYPE_IDHANDPIC);
                }
                break;
        }
    }

    @Override
    public void showViewData(DefBankOutput output) {
        if (output != null) {
            showLoadingDialog(false, "正在加载图片，请稍后...");
            parseAndDisplayImage(output.getCrdFroPic(), crdFroIv, crdFroCloud, CommonConfig.TYPE_CRDFROPIC);
            parseAndDisplayImage(output.getCrdConPic(), crdConIv, crdConCloud, CommonConfig.TYPE_CRDCONPIC);
            parseAndDisplayImage(output.getIdHandPic(), handIv, handCloud, CommonConfig.TYPE_IDHANDPIC);
        }
    }

    @Override
    public void showOcrBankViewData(DefBankOcrOutput ocrOutput, boolean isNeedUpload) {
        this.isNeedUpload = isNeedUpload;
        this.mOcrOutput = ocrOutput;
        if (mOcrOutput != null) {
            mOcrOutput.setOriginalCardNo(mOcrOutput.getCardNo());
            CardOpenProvider.getInstance().openUpdateBankSecondActivity(mContext, mOcrOutput);
        }
    }

    /**
     * 照片回显
     */
    private void parseAndDisplayImage(String imageUrl, ImageView imageView, TextView textView, String fileName) {
        if (!TextUtils.isEmpty(imageUrl)) {
            String imgUrl = UrlConstants.getBaseUrl() + imageUrl + RequestMap.sessionIdReqStr();
            imageView.setTag(imgUrl);
            JKImageLoader.getInstance().displayImage(getContext(), imgUrl, imageView);
            textView.setVisibility(View.VISIBLE);
            mPresenter.getImageFileByNet(imgUrl, fileName);
        }
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            ArrayList<String> photos =
                    data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            switch (requestCode) {
                case CommonConfig.REQUESTCODE_DEFBANK_VIEW_CRDFRO:
                    if (photos == null || photos.size() == 0) {
                        crdFroIv.setTag(null);
                        crdFroIv.setImageDrawable(null);
                        crdFroCloud.setVisibility(View.GONE);
                        mPresenter.removeFile(CommonConfig.TYPE_CRDFROPIC);
                        isNeedUpload = true;
                    }
                    break;
                case CommonConfig.REQUESTCODE_DEFBANK_VIEW_CRDCON:
                    if (photos == null || photos.size() == 0) {
                        crdConIv.setTag(null);
                        crdConIv.setImageDrawable(null);
                        crdConCloud.setVisibility(View.GONE);
                        mPresenter.removeFile(CommonConfig.TYPE_CRDCONPIC);
                        isNeedUpload = true;
                    }
                    break;
                case CommonConfig.REQUESTCODE_DEFBANK_VIEW_IDHAND:
                    if (photos == null || photos.size() == 0) {
                        handIv.setTag(null);
                        handIv.setImageDrawable(null);
                        handCloud.setVisibility(View.GONE);
                        mPresenter.removeFile(CommonConfig.TYPE_IDHANDPIC);
                        isNeedUpload = true;
                    }
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ReviewPhotoEvent event) {
        if (event != null) {
            String filePath = event.getFilePath();
            if (TextUtils.isEmpty(filePath)) {
                return;
            }
            String fileIdName;
            switch (event.getCurrentType()) {
                case CommonConfig.TYPE_CRDFROPIC:
                    fileIdName = CommonConfig.TYPE_CRDFROPIC;
                    JKImageLoader.getInstance().displayImage(mContext, "file://" + filePath, crdFroIv);
                    crdFroIv.setTag(filePath);
                    crdFroCloud.setVisibility(View.VISIBLE);
                    isNeedUpload = true;
                    break;
                case CommonConfig.TYPE_CRDCONPIC:
                    fileIdName = CommonConfig.TYPE_CRDCONPIC;
                    JKImageLoader.getInstance().displayImage(mContext, "file://" + filePath, crdConIv);
                    crdConIv.setTag(filePath);
                    crdConCloud.setVisibility(View.VISIBLE);
                    isNeedUpload = true;
                    break;
                case CommonConfig.TYPE_IDHANDPIC:
                    fileIdName = CommonConfig.TYPE_IDHANDPIC;
                    JKImageLoader.getInstance().displayImage(mContext, "file://" + filePath, handIv);
                    handIv.setTag(filePath);
                    handCloud.setVisibility(View.VISIBLE);
                    isNeedUpload = true;
                    break;
                default:
                    return;
            }
            mPresenter.onCompress(filePath, fileIdName);
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        SoftInputUtil.hideSoftInput(this);
    }

    @Override
    public void setPresenter(UpdateDefBankContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtil.deleteCache();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
